<template>
  <div v-loading="loading" class="state">
    <el-form ref="form" :class="isCard ? 'meeting-card' : ''" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row style="flex-wrap: wrap;display: flex">
        <el-col :span="12">
          <el-form-item :label="$t('会议日期')" prop="mtDate">
            <el-date-picker
              v-model="form.mtDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('会议日期')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('会议时间')" prop="mtTime">
            <el-time-picker
              v-model="form.mtTime"
              is-range
              range-separator="-"
              format="HH:mm"
              value-format="HH:mm"
              :picker-options="{
                selectableRange:'00:00 - 23:59'
              }"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')"
              :placeholder="$t('会议时间')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('会议结论')" prop="mtConclusion">
            <template slot="label">
              <span>{{ $t('会议结论') }}</span>
              <el-tooltip effect="dark" placement="right">
                <!--  问号的图标   -->
                <i class="el-icon-question" />
                <!--  提示的内容 -->
                <div slot="content">
                  <span>{{ $t('会议结论由投票结果决定，无法更改') }}</span>
                </div>
              </el-tooltip>
            </template>
            <dict-select
              v-model="form.mtConclusion"
              dictionary="mt_conclusion"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.mtConclusion !== 'BTG'" :span="12">
          <el-form-item :label="$t('投资主体')" prop="investmentId">
            <el-select v-model="form.investmentId" filterable :clearable="true" disabled :placeholder="$t('请选择')">
              <el-option
                v-for="item in investmentList"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.mtConclusion !== 'BTG' && !form.icMeetingId" :span="12">
          <el-form-item :label="$t('投资金额') + $t('金额单位')" prop="investmentAmount">
            <Money v-model="form.investmentAmount" unit="w" :placeholder="$t('投资金额') + $t('金额单位')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('会议纪要邮件正文')" prop="mtComment">
            <EditorTxt v-if="!loading" v-model="form.mtComment" :height="400" :placeholder="$t('会议纪要邮件正文')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--交办事项-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('交办事项') }}</span>
      </div>
      <el-table :data="form.mtTaskList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('事项内容')" align="center" min-width="200">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('事项内容') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'mtTaskList.' + scope.$index + '.matterComment'" :rules="mtTaskListRules.matterComment">
              <el-input v-model="scope.row.matterComment" :placeholder="$t('事项内容')" show-word-limit maxlength="200" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('跟进人')" align="center" min-width="200">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('跟进人') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'mtTaskList.' + scope.$index + '.userId'" :rules="mtTaskListRules.userId">
              <UserSelect v-model="scope.row.userId" popper-append-to-body multiple filterable :placeholder="$t('跟进人')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addHandle">{{ $t('添加交办事项') }}</el-button>
      </div>
      <FileTable ref="fileTable" :business-id="form.dealId" :list.sync="form.fileList" data-type="mt_conclusion" :btn-show="!otherBtnHide" />
      <div v-if="form.actId && !hideFlow" class="flow-svg">
        <div class="actTaskLeft actTaskForm">
          <!--流转记录-->
          <div>
            <approval-record :act-id="form.actId" />
          </div>
        </div>
        <div class="actTaskLeft">
          <!--流程图-->
          <act-flow-chart :act-id="form.actId" />
        </div>
      </div>
    </el-form>
    <div v-if="source !== 'sheet' || isBussiness" slot="footer" :style="{'margin-top':isBussiness ? '20px': ''}" class="dialog-footer" style="text-align: right;">
      <el-button v-if="!isBussiness" @click="cancel()">{{ $t("取消") }}</el-button>
      <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" type="primary" @click="submitForm(processKey ? 'process' : 'save')">{{ $t("确认结论") }}</el-button>
    </div>
    <!--    <el-dialog v-if="meetingFlowOpen" :title="$t('流程记录')" :visible.sync="meetingFlowOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>-->
    <!--      <div>-->
    <!--        <div class="actTaskLeft actTaskForm">-->
    <!--          &lt;!&ndash;流转记录&ndash;&gt;-->
    <!--          <div>-->
    <!--            <approval-record :act-id="form.actId" />-->
    <!--          </div>-->
    <!--        </div>-->
    <!--        <div class="actTaskLeft">-->
    <!--          &lt;!&ndash;流程图&ndash;&gt;-->
    <!--          <act-flow-chart :act-id="form.actId" />-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <div v-if="form.actId && hideFlow">
      <div class="actTaskLeft actTaskForm">
        <!--流转记录-->
        <div>
          <approval-record :act-id="form.actId" />
        </div>
      </div>
      <div class="actTaskLeft">
        <!--流程图-->
        <act-flow-chart :act-id="form.actId" />
      </div>
    </div>
  </div>
</template>

<script>
import { saveMtConclusion, getMtConclusion, getMtConclusionByMeetingId, delMtTask } from '@/api/deal/meeting/conclusion/mtConclusion'
import { findFund } from '@/api/fund/fundBase'
import { getConfigByMeetingId, getProcessKeyByMeetingType } from '@/api/meeting/config/mtPersonConfig'
import mixin from '@/views/deal/mt/mixin/mixin'
import ActFlowChart from '@/views/act/process/actFlowChart'

import ApprovalRecord from '@/components/Act/ApprovalRecord/index.vue'
import EditorTxt from '@/components/Tinymce'
export default {
  components: { EditorTxt, ApprovalRecord, ActFlowChart },
  mixins: [mixin],
  props: {
    ...mixin,
    meetingId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 表单参数
      form: {
        mtTime: [],
        mtTaskList: [],
        fileList: []
      },
      // 投资主体列表
      investmentList: [],
      // 遮罩层
      loading: false,
      isBussiness: false,
      // 表单校验
      rules: {
        mtDate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        mtTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        mtConclusion: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        investmentId: [
          { required: true, message: this.$t('必填信息'), trigger: 'change' }
        ],
        investmentAmount: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        mtComment: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      mtTaskListRules: {
        matterComment: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        userId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      // 操作按钮默认不展示
      buttonShow: true,
      otherBtnHide: false,
      // 对应流程
      processKey: undefined,
      // 申请标题
      actTitle: undefined,
      isCard: false,
      hideFlow: false,
      dealId: undefined,
      meetingFlowOpen: false,
      disabled: true
    }
  },
  created() {
    this.$bus.$emit('async_meeting_done')
    this.$bus.$emit('async_done')
    findFund({}).then((response) => {
      if (response.data) {
        this.investmentList = response.data
      }
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      this.isCard = data && data.isCard
      if (data.wfNodeId) {
        this.isBussiness = true
      }
      if (data.meetingId !== undefined) {
        getMtConclusionByMeetingId(data.meetingId).then(response => {
          this.getVoteStatus(data.meetingId)
          this.dealId = response.data.dealId
          if (response.data) {
            console.log(response.data, 'response.data')
            // this.form = response.data
            if (response.data.fileList == null || response.data.fileList.length === 0) {
              response.data.fileList = this.$refs.fileTable.fileConfigArray
            }
            this.$set(this, 'form', response.data)

            this.$parent.form = this.form
            this.actTitle = response.data.actTitle
          } else {
            this.reset()
            this.actTitle = data.actTitle
            this.form.fileList = this.$refs.fileTable.fileConfigArray
            this.form.meetingId = data.meetingId
            this.form.mtDate = data.mtDate
            this.form.meetingType = data.meetingType
            this.$parent.form = this.form
          }
          getProcessKeyByMeetingType(this.form.meetingType).then(res => {
            this.processKey = res.msg
            if (data.wfNodeId) {
              this.hideFlow = true
              if (this.$parent.$parent.$parent.$parent.$parent.$parent?.hideProcess) {
                this.$parent.$parent.$parent.$parent.$parent.$parent.hideProcess(false)
              }
            }
          })
          if (this.form.mtTime) {
            this.form.mtTime = this.form.mtTime.split('-')
          }
          // this.checkFileList(this.form.fileList)
          this.$parent.form = this.form
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else if (data.id !== undefined) {
        getMtConclusion(data.id).then(response => {
          // this.form = response.data
          if (response.data.fileList == null || response.data.fileList.length === 0) {
            response.data.fileList = this.$refs.fileTable.fileConfigArray
          }
          this.$set(this, 'form', response.data)
          this.dealId = response.data.dealId
          this.form.mtTime = response.data.mtTime.split('-')
          // this.checkFileList(this.form.fileList)
          this.$parent.form = this.form
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.dealId = this.$route.query.id
        this.reset()
        this.loading = false
      }
    },
    /**
     * 查询是否开启投票
     */
    getVoteStatus(meetingId) {
      getConfigByMeetingId(meetingId).then(res => {
        this.disabled = res.data.voteFlag === 'Y'
      })
    },
    // 查看流程
    lookFlow() {
      this.meetingFlowOpen = true
    },
    checkFileList(fileList) {
      var fileArr = []
      var checkFileList = this.$refs.fileTable.fileConfigArray

      if (!this.form.fileList || this.form.fileList.length === 0) {
        this.$set(this.form, 'fileList', checkFileList)
        checkFileList.forEach(item => {
          item.businessId = this.form.dealId
        })
      } else {
        // checkFileList.forEach(checkFile => {
        //   var flag = false
        //   fileList.forEach(item => {
        //     console.log(item.directoryId === checkFile.directoryId, item.id, item)
        //     if (item.directoryId === checkFile.directoryId && item.name && item.name.length > 0 && (item.fileId || item.id)) {
        //       flag = true
        //       fileArr.push(item)
        //     }
        //   })
        //   if (!flag) {
        //     checkFile.businessId = this.form.dealId
        //     fileArr.push(checkFile)
        //   }
        // })
        fileList.forEach(item => {
          var flag = false
          checkFileList.forEach(checkFile => {
            console.log(item, flag, checkFile)
          })
        })
        console.log(fileArr, '这里数据是什么')
        this.$set(this.form, 'fileList', fileArr)
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        meetingId: undefined,
        mtDate: undefined,
        mtTime: [],
        mtConclusion: undefined,
        icMeetingId: undefined,
        investmentId: undefined,
        investmentAmount: undefined,
        mtComment: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        fileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.mtConclusionOpen = false
      if (this.$parent.$parent?.meetingCommentOpen !== undefined) {
        this.$parent.$parent.meetingCommentOpen = false
      }
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.mtConclusionOpen !== undefined) {
        this.$parent.$parent.mtConclusionOpen = false
      }
      if (this.$parent.$parent?.meetingCommentOpen !== undefined) {
        this.$parent.$parent.meetingCommentOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // // 保存数据
            // var indexs = []
            // this.form.fileList.forEach((item, index) => {
            //     if (!item.id) {
            //       indexs.push(index)
            //     }
            // })
            // indexs.forEach(i => {
            //   this.form.fileList.splice(i, 1)
            // })
            this.form.mtTime = this.form.mtTime.join('-')
            saveMtConclusion(this.form).then(response => {
              if (response.code === 200) {
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 启动流程
                  this.form.id = response.data.id
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      }).catch(() => {
        this.loading = false
      })
    },
    // 启动流程
    startProcess(data) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.actTitle
      // 业务表名
      processData.dataTable = 'mt_conclusion'
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/deal/mt/conclusion/mtConclusionForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = 'mt_conclusion'
      // processKey 流程配置
      processData.processKey = this.processKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 删除交办事项
    delHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delMtTask(id)
          }).then(() => {
          this.form.mtTaskList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.form.mtTaskList.splice(index, 1)
      }
    },
    // 添加交办事项
    addHandle() {
      const row = {
        id: undefined,
        conclusionId: undefined,
        matterComment: undefined,
        userId: [],
        remark: undefined
      }
      if (!(this.form.mtTaskList instanceof Array)) {
        this.$set(this.form, 'mtTaskList', [])
      }
      this.$nextTick(() => {
        this.form.mtTaskList.push(row)
      })
    },
    switchMtConclusion() {
      this.form.investmentId = undefined
      this.form.investmentAmount = undefined
    }
  }
}
</script>
<style scoped lang="scss">
/deep/.dataForm .avatar-uploader{
  display: none;
}
/deep/.flow-svg .actTaskLeft{
  padding-left: 0 !important;
}
</style>
